package org.grapes.wine.api.server.startup;

import java.io.File;

import javax.naming.InitialContext;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;

public class InitSessionFactory {

	private InitSessionFactory() {
	}

	private static String CONFIG_FILE_LOCATION = "WebContent/WEB-INF/hibernate.cfg.xml";

	private static final Configuration cfg = new Configuration();

	private static SessionFactory sessionFactory;
	
	public static void setConfigFileLocation(String path) {
		CONFIG_FILE_LOCATION = path;
	}
	
	public static SessionFactory getInstance() {
		if (sessionFactory == null)
			initSessionFactory();
		return sessionFactory;
	}

	public Session openSession() {
		return sessionFactory.openSession();
	}

	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	private static synchronized void initSessionFactory() {
		/*
		 * check again for null because sessionFactory may have been initialized
		 * between the last check and now
		 */
		Logger log = Logger.getLogger(InitSessionFactory.class);
		if (sessionFactory == null) {
			try {
				cfg.configure(new File(CONFIG_FILE_LOCATION));
				String sessionFactoryJndiName = cfg
						.getProperty(Environment.SESSION_FACTORY_NAME);
				if (sessionFactoryJndiName != null) {
					cfg.buildSessionFactory();
					log.debug("get a jndi session factory");
					sessionFactory = (SessionFactory) (new InitialContext())
							.lookup(sessionFactoryJndiName);
				} else {
					log.debug("classic factory");
					sessionFactory = cfg.buildSessionFactory();
				}
			} catch (Exception e) {
				System.err.println("Error Creating HibernateSessionFactory");
				e.printStackTrace();
				throw new HibernateException(
						"Could not initialize the Hibernate configuration");
			}
		}
	}

	public static void close() {
		if (sessionFactory != null)
			sessionFactory.close();
		sessionFactory = null;
	}
}
